#include <stdio.h>
#include <stdlib.h>
#include <wand/MagickWand.h>

#define MAX 1000

int mandelbrot(double x, double y)
{
    int d;
    double x0 = x, y0 = y;
    double xn, yn;
    for(d = 0; d < MAX; d++)
    {
        xn = x*x - y*y +x0;
        yn = 2*x*y + y0;
        if (xn == x && yn == y)
            return MAX;
        if (x*x + y*y > 4)
            return d;
        x = xn;
        y = yn;
    }
    return d;    
}

// assume RGB
void set_color(char*pos, int depth)
{
    int range = MAX/3 + 1;
    pos[0] = pos[1] = pos[2] = 0;
    if (depth == MAX)
        return;
    int intensity = (MAX-depth) / 3;
    int color = depth % 3;
    pos[color] = 255-intensity;
}

void do_it()
{
    MagickWand* wand;
    const int width = 1000;
    const int height = 760;
    char* data = malloc(width * height * 3);
    int x,y;
    double x1 = -2, x2 = 1;
    double y1 = 1, y2 = -1;
    double xd = (x2-x1)/(width-1);
    double yd = (y2-y1)/(height-1);    
    int val;
    
    for(x = 0; x < width; x++)
    {
        for(y = 0; y < height; y++)
        {
            val = mandelbrot(x1 + x*xd, y1+y*yd);
            set_color(data + 3*(y*width + x), val);
        }
    }
    
    wand = NewMagickWand();
    MagickConstituteImage(wand, width, height, "RGB", CharPixel, data);
    MagickWriteImage(wand, "mandel.png");
    ClearMagickWand(wand);
    free(data);
    
}



int main(int ac, char**av) 
{
    MagickWandGenesis();
    do_it();
    MagickWandTerminus();
    return 0;
}

